package com.unisound.tracelog.client.core.support.pool;


import com.unisound.tracelog.client.core.properties.TraceLogClientProperties;
import com.unisound.tracelog.client.core.util.SpringUtil;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class TraceLogThreadPoolManager {

    private static final int cpuCoreNumber = Runtime.getRuntime().availableProcessors();
    private static TraceLogClientProperties traceLogClientProperties = SpringUtil.getBean(TraceLogClientProperties.class);

    public static ExecutorService newTraceLogThreadPool() {
        ThreadPoolExecutor executor = new ThreadPoolExecutor(
                getPoolMinThreadNumber(),
                getPoolMaxThreadNumber(),
                0, TimeUnit.SECONDS,
                new LinkedBlockingQueue<>(getPoolQueueSize()),
                new TraceLogThreadFactory("TraceLog"), new TraceLogDiscardOldestPolicy());
        return executor;
    }

    private static int getPoolMinThreadNumber() {
        int poolMinThreadNumber = traceLogClientProperties.getPoolMinThreadNumber();
        if (poolMinThreadNumber <= 0 || poolMinThreadNumber > cpuCoreNumber) return 1;
        return poolMinThreadNumber;
    }

    private static int getPoolMaxThreadNumber() {
        int poolMaxThreadNumber = traceLogClientProperties.getPoolMaxThreadNumber();
        if (poolMaxThreadNumber <= 0 || poolMaxThreadNumber > cpuCoreNumber) return 1;
        return poolMaxThreadNumber;
    }

    private static int getPoolQueueSize() {
        int poolQueueSize = traceLogClientProperties.getPoolQueueSize();
        if (poolQueueSize <= 0 || poolQueueSize > 500) return 500;
        return poolQueueSize;
    }

}
